package com.zhangpengkai.controller;

import com.zhangpengkai.domain.User;
import com.zhangpengkai.service.impl.RoleServiceImpl;
import com.zhangpengkai.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@WebServlet("/user")
public class UserController extends HttpServlet{

//    @Autowired
//    UserService userService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username") == null ? "" : req.getParameter("username");
        String password = req.getParameter("password") == null ? "" : req.getParameter("password");

        User user1 = new User(username,password);

        UserServiceImpl userService = (UserServiceImpl) WebApplicationContextUtils.
                getWebApplicationContext(getServletContext()).
                getBean("userServiceImpl");



        RoleServiceImpl roleServiceImpl = (RoleServiceImpl) WebApplicationContextUtils.
                getWebApplicationContext(getServletContext()).
                getBean("roleServiceImpl");
        User user = userService.selectUser(username);
        //查询登录用户的权限
        Integer roleId = roleServiceImpl.selectRoleById(user.getId());

        if(userService.login(user1)){
            System.out.println("登录成功");

            if(roleId == 1){
                resp.sendRedirect("/jsp/list.jsp");
            } else if (roleId == 2) {
                resp.sendRedirect("/jsp/user.jsp");
            } else if (roleId == 3) {
                resp.sendRedirect("/jsp/vip.jsp");
            }

            resp.sendRedirect("/jsp/list.jsp");
        } else {
            System.out.println("登录失败");
            resp.sendRedirect("index.jsp");
        }

    }
}
